package homework.jdbc.dao;

import homework.jdbc.domain.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by Administrator on 2017/9/13.
 */

     //操作User表
public class UserDao {
    public List<User> findAll(int id){
        Connection con=JDBCUtils.getConnection();
        User user=new User();
        //ArrayList<User> list=new ArrayList();
        ResultSet result= null;
        //Statement statement= null;
        PreparedStatement ps=null;

        try{
            String sql="select * from user where id=?";
            ps=con.prepareStatement(sql);
            ps.setInt(1,id);
            //statement=con.createStatement();
            //String sql="select * from user";
             result=ps.executeQuery();
            while(result.next()){

                user.setId(result.getInt(1));
                user.setUsername(result.getString(2));
                user.setPassword(result.getString(3));
                return user;
            }
        }catch(SQLException e){
            e.printStackTrace();
        }finally {
            if (result!=null) {
                    try {
                        result.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        return null;
    }

    public boolean insert(User user){
        Connection connection=JDBCUtils.getConnection();
        String sql="insert into user(id,username,password) values(?,?,?)";
        PreparedStatement ps=null;
            try {
                ps=connection.prepareStatement(sql);
                ps.setInt(1,user.getId());
                ps.setString(2,user.getUsername());
                ps.setString(3,user.getPassword());
                int num=ps.executeUpdate();
                if(num==1){
                    return true;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        return false;
    }
    public boolean update(){
        return false;
    }
    public boolean delete(){
        return false;
    }
    public User findById(int i){
        return null;
    }
}
